<template>
  <view class="edit-field-container">
    <!-- Custom Navigation Bar -->
    <view class="custom-nav-bar">
      <view class="nav-bar-left" @click="goBack">
        <text class="iconfont icon-back">←</text>
      </view>
      <view class="nav-bar-title">
        <text>{{ pageTitle }}</text>
      </view>
      <view class="nav-bar-right">
        <!-- 移除顶部保存按钮 -->
      </view>
    </view>
    
    <!-- Edit Content -->
    <view class="edit-content">
      <!-- Text input for nickname and intro -->
      <view v-if="field === 'nickname' || field === 'intro'" class="text-input-wrapper">
        <input 
          v-if="field === 'nickname'" 
          class="text-input" 
          type="text" 
          v-model="fieldValue" 
          placeholder="请输入您的名字"
          maxlength="20"
        />
        <view class="char-counter" v-if="field === 'nickname'">
          {{ fieldValue.length }}/20
        </view>
      </view>
      
      <!-- Sex selection -->
      <view v-if="field === 'sex'" class="radio-group-wrapper">
        <view class="radio-option" :class="{ 'selected': fieldValue === 1 }" @click="fieldValue = 1">
          <text>男</text>
          <text class="radio-check" v-if="fieldValue === 1">✓</text>
        </view>
        <view class="radio-option" :class="{ 'selected': fieldValue === 2 }" @click="fieldValue = 2">
          <text>女</text>
          <text class="radio-check" v-if="fieldValue === 2">✓</text>
        </view>
      </view>
      
      <!-- Birthday picker -->
      <view v-if="field === 'birthday'" class="date-picker-wrapper">
        <picker 
          mode="date" 
          :value="fieldValue" 
          start="1900-01-01" 
          end="2023-12-31" 
          @change="onDateChange"
        >
          <view class="date-picker">
            <text>{{ fieldValue || '请选择日期' }}</text>
          </view>
        </picker>
      </view>
      
      <!-- Location picker -->
      <view v-if="field === 'location'" class="location-picker-wrapper">
        <picker 
          mode="region" 
          :value="fieldValue.split(' ')" 
          @change="onRegionChange"
        >
          <view class="location-picker">
            <text>{{ fieldValue || '请选择地区' }}</text>
          </view>
        </picker>
      </view>
      
      <!-- bgUrl image selection -->
      <view v-if="field === 'bgUrl'" class="bg-selection-wrapper">
        <view class="current-bg">
          <image class="bg-preview" :src="fieldValue || '/static/images/bg-thumbnail.jpg'" mode="aspectFill"></image>
        </view>
        <view class="choose-btn" @click="chooseImage">选择图片</view>
      </view>

      <!-- Community name input -->
      <view v-if="field === 'communityName'" class="text-input-wrapper">
        <input 
          class="text-input" 
          type="text" 
          v-model="fieldValue" 
          placeholder="请输入社区名称"
          maxlength="20"
        />
      </view>
    </view>
    
    <!-- 底部保存按钮 -->
    <view class="bottom-save-btn">
      <button class="save-btn" @click="saveField">保存</button>
    </view>
  </view>
</template>

<script>
import { updateUserInfo, uploadFile } from '@/api/api.js';
export default {
  data() {
    return {
      field: '',
      fieldValue: '',
      pageTitle: '编辑'
    }
  },
  onLoad(options) {
    // Get field type and current value from parameters
    if (options.field) {
      this.field = options.field;
      this.fieldValue = options.value || '';
      
      // Set page title based on field type
      switch(this.field) {
        case 'nickname':
          this.pageTitle = '编辑名字';
          break;
        case 'intro':
          this.pageTitle = '编辑简介';
          break;
        case 'sex':
          this.pageTitle = '选择性别';
          break;
        case 'birthday':
          this.pageTitle = '选择生日';
          break;
        case 'location':
          this.pageTitle = '选择地区';
          break;
        case 'bgUrl':
          this.pageTitle = '更换背景图';
          break;
        case 'communityName':
          this.pageTitle = '编辑社区名称';
          break;
        default:
          this.pageTitle = '编辑';
      }
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    saveField() {
      // Validate field value if needed
      if (this.field === 'nickname' && !this.fieldValue.trim()) {
        uni.showToast({
          title: '名字不能为空',
          icon: 'none'
        });
        return;
      }
      
      // 获取缓存中的用户信息
      const userInfo = uni.getStorageSync('userInfo') || {};
      
      // 更新特定字段
      userInfo[this.field] = this.fieldValue;
      
      // 更新数据
      const data = {
        [this.field]: this.fieldValue
      };
      
      uni.showLoading({
        title: '保存中...'
      });
      
      // 保存到缓存
      uni.setStorageSync('userInfo', userInfo);
      
      // 使用API更新用户信息
      console.log(data);
      updateUserInfo(data).then(res => {
        console.log(res);
        uni.hideLoading();
        
        // 使用事件通道通知上一页面编辑完成
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];
        if (prevPage && prevPage.$vm) {
          prevPage.$vm.editComplete = true;
        }
        
        uni.navigateBack({
          success: () => {
            uni.showToast({
              title: '保存成功',
              icon: 'success'
            });
          }
        });
      }).catch(err => {
        uni.hideLoading();
        console.error('更新用户信息失败:', err);
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        });
      });
    },
    onDateChange(e) {
      this.fieldValue = e.detail.value;
    },
    onRegionChange(e) {
      // Convert array ['中国', '山东', '济南'] to string '中国 山东 济南'
      this.fieldValue = e.detail.value.join(' ');
    },
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // For demo purposes, we'll just set the local path
          // In a real app, you'd upload this to a server
          uploadFile(res.tempFilePaths[0]).then(res => {
            this.fieldValue = res.data;
            console.log(this.fieldValue);
          });
        }
      });
    }
  }
}
</script>

<style scoped>
.edit-field-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  position: relative;
  padding-bottom: 80px; /* 为底部按钮留出空间 */
}

.custom-nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 44px;
  padding: 0 16px;
  background-color: #ffffff;
  position: sticky;
  top: 0;
  z-index: 100;
  /* Safe area inset for different devices */
  padding-top: calc(20px + var(--status-bar-height, 0px));
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.nav-bar-left, .nav-bar-right {
  min-width: 60px;
}

.nav-bar-left {
  display: flex;
  align-items: center;
}

.icon-back {
  font-size: 20px;
}

.nav-bar-title {
  font-size: 18px;
  font-weight: 500;
}

.nav-bar-right {
  display: flex;
  justify-content: flex-end;
}

.edit-content {
  padding: 20px 16px;
}

.text-input-wrapper, .radio-group-wrapper, .date-picker-wrapper, 
.location-picker-wrapper, .bg-selection-wrapper {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.text-input {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border: none;
  border-bottom: 1px solid #eeeeee;
}

.text-area {
  width: 100%;
  height: 120px;
  font-size: 16px;
  border: 1px solid #eeeeee;
  border-radius: 4px;
  padding: 8px;
}

.char-counter {
  text-align: right;
  font-size: 14px;
  color: #999;
  margin-top: 8px;
}

.radio-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #eeeeee;
}

.radio-option:last-child {
  border-bottom: none;
}

.radio-option.selected {
  color: #2196f3;
}

.radio-check {
  color: #2196f3;
}

.date-picker, .location-picker {
  height: 44px;
  display: flex;
  align-items: center;
  font-size: 16px;
}

.bg-preview {
  width: 100%;
  height: 200px;
  border-radius: 8px;
  margin-bottom: 16px;
  background-color: #e0e0e0;
}

.choose-btn {
  background-color: #2196f3;
  color: #ffffff;
  border-radius: 4px;
  height: 44px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
}

/* 底部保存按钮样式 */
.bottom-save-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 80px;
  background-color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px 16px;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
  z-index: 99;
}

.save-btn {
  width: 100%;
  height: 50px;
  background-color: #07c160;
  color: #ffffff;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: none;
}
</style>
